package uppacket

import (
	"time"

	"gitee.com/yanwc/ebike-xiaoan-device/device"
	"gitee.com/yanwc/ebike-xiaoan-device/device/config"
	"gitee.com/yanwc/ebike-xiaoan-device/internal/codec"
	"gitee.com/yanwc/ebike-xiaoan-device/internal/field"
	"gitee.com/yanwc/ebike-xiaoan-device/internal/frame"
	"gitee.com/yanwc/net/utils"
	"github.com/panjf2000/gnet"
)

type LoginPacket struct{}

func (hbp *LoginPacket) Login(
	frame frame.IFrame,
	c gnet.Conn,
	cfg config.ServerConfig,
) ([]byte, gnet.Action, error) {
	var version field.FirmwareVersionRaw
	var deviceTypeRaw field.DeviceTypeRaw
	var imei field.IMEIRaw
	var imsi field.IMSIRaw
	utils.LoadPacket(frame.Content(), version[:], deviceTypeRaw[:], imei[:], imsi[:])
	d := device.NewDevice(
		c,
		version.Type(),
		imei.Type(),
		imsi.Type(),
		deviceTypeRaw.Type(),
		cfg.OnEventNotify,
		cfg.OnStatusNotify,
		cfg.OnHeartBeatNotify)
	device.SessionDevices.Add(imei.Type(), d)
	if cfg.OnLoginNotify != nil {
		go cfg.OnLoginNotify(config.Context{
			Imei:            imei.Type(),
			Imsi:            imsi.Type(),
			FirmwareVersion: version.Type(),
		}, cfg.Url)
	}

	timestamp := time.Now().Unix()
	f := &codec.Frame{
		Header: &codec.Header{
			CmdWord: frame.GetCmdWord(),
			SN:      frame.GetSN(),
		},
	}

	return f.WrapPacket(utils.NumberToBytesWithBigEndian[uint32](uint32(timestamp))), gnet.None, nil
}
